﻿﻿/**
 *  
 */
define([
        "dojo/_base/declare","dojo/_base/lang","dojo/_base/array","dojo/topic",
        "gistech/widgets/normalDialog/NormalDialog",
        "dojo/text!./templates/BookMark.html",
        "dojo/text!./templates/rowContainer.html",
        "gistech/widgets/drawGeometryWidget/DrawGeometryWidget","esri/layers/FeatureLayer","esri/graphic","esri/tasks/QueryTask", 
        "esri/tasks/query","esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol", 
        "esri/symbols/SimpleFillSymbol","esri/symbols/TextSymbol","esri/Color","esri/geometry/Extent","dojo/on","gistech/widgets/bookMark/BookMarkEdit"],
        function(declare,lang,array,topic,NormalDialog,template,rowTemplate,DrawGeometryWidget,FeatureLayer,Graphic,QueryTask,ArcQuery,SimpleMarkerSymbol, SimpleLineSymbol,
        		SimpleFillSymbol, TextSymbol,Color,Extent,on,BookMarkEdit){
            return declare([NormalDialog],{
            	map:null,
                count:1, //count表示未命名的书签数量
                lcBodyClick:null,//单击body的事件句柄
                storageKey:"bookMarks",
                hasConfig:false,
                templateString:template,
                symbols:{},
                nowUserBookMarkNames:[],//当前所有书签名
                userBookMarkNames:[],//初始化查询所有书签名
                editBookName:null,//编辑前的书签名
                nowRowContainer:null,
                constructor:function (args) {
                	this.inherited(arguments);
                	this.resetAttr();
                	Global.widgets.BK={};
        			this.symbols.point = new SimpleMarkerSymbol("circle", 10, new SimpleLineSymbol(), new Color([255, 0, 0, 0.75]));
        			this.symbols.polyline = new SimpleLineSymbol("solid", new Color([255, 0, 0]), 2);
        			this.symbols.polygon = new SimpleFillSymbol().setColor(new Color([255,0,0,0.25]));
        			this.symbols.extent = new SimpleFillSymbol().setColor(new Color([255,0,0,0.25]));
        			
//                    this.bookMarkPointLayerUrl="http://landa:6080/arcgis/rest/services/ppoint5/FeatureServer/0";
//                    this.bookMarkLineLayerUrl="http://localhost:6080/arcgis/rest/services/bookmark/FeatureServer/1";
//                    this.bookMarkPolygonLayerUrl="http://localhost:6080/arcgis/rest/services/bookmark/FeatureServer/2";
        			
        			//书签对应的服务地址
                    this.bookMarkPointLayerUrl="http://10.1.10.230:6080/arcgis/rest/services/SL/BOOKMARK/FeatureServer/0";
                    this.bookMarkLineLayerUrl="http://10.1.10.230:6080/arcgis/rest/services/SL/BOOKMARK/FeatureServer/3";
                    this.bookMarkPolygonLayerUrl="http://10.1.10.230:6080/arcgis/rest/services/SL/BOOKMARK/FeatureServer/4";
                    
                    //lan机器
//                    this.bookMarkPointLayerUrl="http://localhost:6080/arcgis/rest/services/book_mark/FeatureServer/0";
//                    this.bookMarkLineLayerUrl="http://localhost:6080/arcgis/rest/services/book_mark/FeatureServer/1";
//                    this.bookMarkPolygonLayerUrl="http://localhost:6080/arcgis/rest/services/book_mark/FeatureServer/2";
                    
                    
                    this.pointLayer = new FeatureLayer(this.bookMarkPointLayerUrl,{});
                    this.lineLayer = new FeatureLayer(this.bookMarkLineLayerUrl,{});
                    this.polygonLayer = new FeatureLayer(this.bookMarkPolygonLayerUrl,{});
                    
                }, 
                
                resetAttr:function(){
                	this.count = 1;
                	if(this.lcBodyClick){
                		dojo.disconnect(this.lcBodyClick);
                	}
                	this.lcBodyClick = null;
                },

                postCreate:function () {
                	this.inherited(arguments);
                    this.setTitle("书签");
                    this.initBookMarksByDB();
                    
                    on(this.btnAdd, "click",lang.hitch(this,this.createNewBookMark));
                    topic.subscribe('saveBK',lang.hitch(this,this._createOrEditBookMark));
                    this.lcBodyClick = dojo.connect(document.body, "onclick", this, this.handleInputBlur);
                    //dojo.addOnUnload(this, this.saveBookMarks);  
            		Global.currentDraw="landExpandManager";
            		var drawGeometryWidget = new DrawGeometryWidget({map:Global.widgets.mapWidget.map,id:"BookMark"});
                	drawGeometryWidget.startup();
//                	Global.bbq = topic;
//                	topic.subscribe('bbq',lang.hitch(this,this.initProjectData));
//                	this.initProjectData(a,b);
                },


                handleInputBlur:function (evt) {
                    var target = evt.target || evt.srcElement;
                    if (!dojo.hasClass(target, "inputChangeName")) {
                        var inputs = dojo.query(".inputChangeName", this.allRowsContainer);
                        for (var i = 0; i < inputs.length; i++) {
                            var inputChangeName = inputs[i];
                            var display = dojo.style(inputChangeName, "display");
                            if (display == "block") {
                                inputChangeName.blur();//主动失去焦点
                            }
                        }
                    }
                },

                createNewBookMark:function (evt) {
                	this.createOrEditBookMarkDiag(null,null,null);
                },
                
                addBookMark:function (name,remark,flag) {
                	 
                    try{
                    	//   name 不能重复
                    	 
                    	var isExist = false; 
	        			
        				if(this.nowUserBookMarkNames.length==0){
    					   this.nowUserBookMarkNames.push(name);
    					   
        				}else{
                			array.forEach(this.nowUserBookMarkNames,lang.hitch(this,function(bookMarkName){
                  				 if(name == bookMarkName){
//                  					 alert('已经存在书签名称,不能添加')
                  					isExist = true;
                  				 }
                   			}));
                			
        				}
                    	
        				if(isExist){
        					if(flag){
        						alert('已经存在书签名称,不能重复');
        					}
        					return;
        				}else{
        					this.nowUserBookMarkNames.push(name);
        				}
            			
        				
                    	
                        var rowHtml = rowTemplate;
                        var rowContainer = dojo.create("div", {
                            innerHTML:rowHtml,
                            className:'rowContainer'
                        });
                        var row = dojo.query(".row", rowContainer)[0];
                        var rowInfo = dojo.query(".rowInfo", rowContainer)[0];
                        var edit = dojo.query(".edit", rowContainer)[0];
                        var remove = dojo.query(".remove", rowContainer)[0];
                        var inputChangeName = dojo.query(".inputChangeName", rowContainer)[0];
                        var inputID = dojo.query(".inputID", rowContainer)[0];
                        var inputRemark = dojo.query(".inputRemark", rowContainer)[0];
                        rowInfo.innerHTML = name;
                        inputChangeName.value = name;
                        inputRemark.value= remark;
                        this.allRowsContainer.appendChild(rowContainer);
                        
                        //保存
                        if(flag){
                        	this.saveBookMarkData(name,remark);
                        }
                        var bname = inputChangeName.value;
                        var condition = "USER_ID="+ioc.map.userInfoData.USERID+" AND BOOKMARK_NAME = '"+bname+"'";
                        
                        //保存成功后不知为何会在地图上清除保存的要素
                        if(flag){
                        	this.getBookData(this.bookMarkPointLayerUrl,condition);
                        	this.getBookData(this.bookMarkLineLayerUrl, condition);
                        	this.getBookData(this.bookMarkPolygonLayerUrl,condition);
                        }
                        
                        
                        //定位
                        dojo.connect(rowInfo, "onclick", this, function (evt) {
                        	//清空Graphic
                        	Global.widgets.mapWidget.map.graphics.clear();
                        	
//                        	var bname = evt.currentTarget.innerText;
                        	condition = "USER_ID="+ioc.map.userInfoData.USERID+" AND BOOKMARK_NAME = '"+evt.target.childNodes[0].nodeValue+"'";
                        	this.getBookData(this.bookMarkPointLayerUrl,condition);
                        	this.getBookData(this.bookMarkLineLayerUrl, condition);
                        	this.getBookData(this.bookMarkPolygonLayerUrl,condition);
 
                        });

                        //单击编辑按钮
                        dojo.connect(edit, "onclick", this, function (evt) {
                        	
                        	var objDIV = dojo.create('div',{innerHTML:evt.target.parentElement.parentElement.innerHTML});
                        	var bName = dojo.query(".rowInfo", objDIV)[0].innerHTML ; 
                        	var bRemark = dojo.query(".inputRemark", objDIV)[0].value ; 
                        	
                        	Global.widgets.BK.editTarget = evt.target;
                        	Global.widgets.BK.editBookName = inputChangeName.value;
                        	this.createOrEditBookMarkDiag("edit",bName,bRemark);
                        	
//                            dojo.style(row, "display", "none");
//                            dojo.style(inputChangeName, "display", "block");
//                            inputChangeName.focus();
//                            
//                            evt.stopPropagation();
                            
                        });


                        
                        //更改名称完成
//                        dojo.connect(inputChangeName, "onblur", this, function () {
//                        	
//                        	
//                            var editFlag = 0;
//                			array.forEach(this.nowUserBookMarkNames,lang.hitch(this,function(bookMarkName){
//	            				 if(trimChangeName == bookMarkName){
//	            					 editFlag++;
//	            				 }
//	            			}));
//                			
//                			if(editFlag>1){
//                   			 layer.msg('已经存在书签名称,不能重复')
//        					 return;
//                			}
//                			
//                            var trimChangeName = dojo.trim(inputChangeName.value);
//                            if (trimChangeName == "") {
//                                trimChangeName = "NewBookmark" + this.count;
//                                this.count++;
//                            }
//                            rowInfo.innerHTML = trimChangeName;
//                            inputChangeName.value = trimChangeName;
//                            dojo.style(inputChangeName, "display", "none");
//                            dojo.style(row, "display", "block");
//                            
//
//                			 
//                            this.updateBookMarkData(this.bookMarkPointLayerUrl,trimChangeName);
//                            this.updateBookMarkData(this.bookMarkLineLayerUrl,trimChangeName);
//                            this.updateBookMarkData(this.bookMarkPolygonLayerUrl,trimChangeName);
//                        });
                        
                        //移除书签
                        dojo.connect(remove, "onclick", this, function (evt) {
                            dojo.destroy(rowContainer);
                            evt.stopPropagation();
                            var delName = evt.currentTarget.previousElementSibling.outerText;
                            
                			array.forEach(this.nowUserBookMarkNames,lang.hitch(this,function(bookMarkName){
	            				 if(delName == bookMarkName){
	            					 this.nowUserBookMarkNames.remove(bookMarkName)
	            				 }
	            			}));
                			
                			
                            //删除数据
                            //删除要素数据
                            this.delBookData(this.bookMarkPointLayerUrl,delName);
                            this.delBookData(this.bookMarkLineLayerUrl,delName);
                            this.delBookData(this.bookMarkPolygonLayerUrl,delName);
                        });
                    }
                    catch(error){
                        console.error("BookMark.addBookMark发生异常:",error);
                    }
                },
        		
        		
                onBeforeClose:function(){
                    try{
                        //this.saveBookMarks();
                        this.resetAttr();
                    }
                    catch(error){
                        console.error("BookMark.onBeforeClose发生异常:",error);
                    }
                },

                startup:function () {
                    this.inherited(arguments);
                },
                
                //保存书签数据
                saveBookMarkData:function(bookMarkName,remark){
                	
                	
                	var graphicsArr = Global.widgets.mapWidget.map.graphics.graphics;
                	var nowExtent  = JSON.stringify(Global.widgets.mapWidget.map.extent);
                	
                	//只保存Extent时
                	if(graphicsArr ==null || graphicsArr.length == 0){
                		graphicsArr=[];
                		var attributes = {
        						EXTENT:nowExtent,
        						BOOKMARK_NAME:bookMarkName,
        						REMARK:remark,
        						USER_ID:ioc.map.userInfoData.USERID,
        				};
                		var aim = new Graphic(null,null,attributes,null)
                		graphicsArr.push(aim);
                	}
                	
                		
                	if(graphicsArr!=null && graphicsArr.length>0){
                		for(var i=0;i<graphicsArr.length;i++ ){
                			
                			//TODO 判断是否在当前界面上  2.可抽取
                			var graphic = graphicsArr[i];
                			//if( graphic.geometry.x==0)continue;
            				graphic.attributes = {
            						EXTENT:nowExtent,
            						BOOKMARK_NAME:bookMarkName,
            						USER_ID:ioc.map.userInfoData.USERID,
            						REMARK:remark
            				}
            				
                			if( graphic.geometry == null ||graphic.geometry.type == "point"){
 	        				
	        				this.pointLayer.applyEdits([graphic],null,null,function(e){
	        					
	        					console.log('point-call-');
	        					console.log(e);
	        					},function(e){
	        						console.log('point-err-'+e);
	        						console.log( e);
	        					}
	        				)
	        				
	        				
                			}else if(graphic.geometry.type == "polyline"){
    	        				this.lineLayer.applyEdits([graphic],null,null,function(e){
    	        					console.log('point-call-');
    	        					console.log(e);
    	        					},function(e){
    	        						console.log('point-err-'+e);
    	        						console.log( e);
    	        					}
    	        				)
                			}else if(graphic.geometry.type == "polygon"){
 
                				this.polygonLayer.applyEdits([graphic],null,null,function(e){ 
                					console.log('polygon-call-'+e);console.log(e)},function(e){
                						console.log('polygon-err-'+e); console.log( e);});
                			}
                		}
                		  
                	} 
                	
                },
                
                
                //删除书签数据
                delBookData:function(url,name){
        			var queryTask=new QueryTask(url); 
        			var condition = "USER_ID="+ioc.map.userInfoData.USERID+" AND BOOKMARK_NAME = '"+name+"'";
        			var query=new ArcQuery();
        			query.returnGeometry=true;
        			query.outFields=["*"];
        			query.where=condition;
        			var delData = [];
        			var type=null ;
        			queryTask.execute(query,lang.hitch(this,function(bookMarkSet){
        				array.forEach(bookMarkSet.features,lang.hitch(this,function(bookMark){
        					delData.push(bookMark)
        					if(bookMark.geometry){
        						type = bookMark.geometry.type;
        					}
        					Global.widgets.mapWidget.map.graphics.clear();
        				}));
        			
        			if( type == "point" || type == null){
        				this.pointLayer.applyEdits(null,null,delData,function(e){
        					
        					console.log('point-del-');
        					console.log(e);
        					},function(e){
        						console.log('point-del-'+e);
        						console.log( e);
        					 }
        					)
        			}else if( type == "polyline"){
        				this.lineLayer.applyEdits(null,null,delData,function(e){
        					
        					console.log('line-del-');
        					console.log(e);
        					},function(e){
        						console.log('line-del-'+e);
        						console.log( e);
        					 }
        					)
        			}else if( type == "polygon"){
 
        				this.polygonLayer.applyEdits(null,null,delData,function(e){ 
        					console.log('polygon-del-'+e);console.log(e)},function(e){
        						console.log('polygon-del-'+e); console.log( e);})
        			}
        			}));
                },
                
 
                
                //编辑书签数据
                updateBookMarkData:function(url,bID,name,remark){
 
        			var queryTask=new QueryTask(url); 
        			var condition = "USER_ID="+ioc.map.userInfoData.USERID+" AND BOOKMARK_NAME = '"+Global.widgets.BK.editBookName+"'";
        			var query=new ArcQuery();
        			query.returnGeometry=true;
        			query.outFields=["*"];
        			query.where=condition;
        			var editData = [];
        			var type = null ;
        			
        			
        			queryTask.execute(query,lang.hitch(this,function(bookMarkSet){
        				array.forEach(bookMarkSet.features,lang.hitch(this,function(bookMark){
        					bookMark.attributes.BOOKMARK_NAME = name;
        					bookMark.attributes.REMARK = remark;
        					editData.push(bookMark);
        					
        					if(bookMark.geometry){
        						type = bookMark.geometry.type;
        					}
        					
        				}));
        			
        			if( type == "point"||type==null){
        				this.pointLayer.applyEdits(null,editData,null,function(e){
        					
        					console.log('point-edit-');
        					console.log(e);
        					},function(e){
        						console.log('point-edit-'+e);
        						console.log( e);
        					 }
        					)
        			}else if( type == "polyline"){
        				this.lineLayer.applyEdits(null,editData,null,function(e){
        					
        					console.log('line-edit-');
        					console.log(e);
        					},function(e){
        						console.log('line-edit-'+e);
        						console.log( e);
        					 }
        					)
        			}else if( type == "polygon"){
 
        				this.polygonLayer.applyEdits(null,editData,null,function(e){ 
        					console.log('polygon-edit-'+e);console.log(e)},function(e){
        						console.log('polygon-edit-'+e); console.log( e);})
        			}
        			}));
                },
                
                //读取数据
                getBookData:function(url,condition){
        			var queryTask=new QueryTask(url); 
        			var query=new ArcQuery();
        			query.returnGeometry=true;
        			query.outFields=["*"];
        			query.where=condition;
        			queryTask.execute(query,lang.hitch(this,function(bookMarkSet){
        				array.forEach(bookMarkSet.features,lang.hitch(this,function(bookMark){
        					
        					if(bookMark.geometry!=null){
	        					
	        					bookMark.setSymbol(this.symbols[bookMark.geometry.type]);
	        					//添加要素
	    						Global.widgets.mapWidget.map.graphics.add(bookMark);
    						
        					}
    						//定位
    						Global.widgets.mapWidget.map.setExtent(new Extent($.parseJSON(bookMark.attributes.EXTENT)));
        				}));
        				
        			}));
                },
                
                //查询 - 初始化创建书签
                initBookMarksByDB:function(){
                	 
                	this.nowUserBookMarkNames=[];
                	this.userBookMarkNames=[];
                	var condition = "USER_ID="+ioc.map.userInfoData.USERID;
                	this.initAllBookMarkData(this.bookMarkPolygonLayerUrl,condition);
                	this.initAllBookMarkData(this.bookMarkPointLayerUrl,condition);
                	this.initAllBookMarkData(this.bookMarkLineLayerUrl,condition);
                },
                
                
                
                initAllBookMarkData:function(url,condition){
        			var queryTask=new QueryTask(url); 
        			var query=new ArcQuery();
        			query.returnGeometry=true;
        			query.outFields=["*"];
        			query.where=condition;
        			queryTask.execute(query,lang.hitch(this,function(bookMarkSet){
        				array.forEach(bookMarkSet.features,lang.hitch(this,function(bookMark){
        					if(bookMark.geometry){
        						bookMark.setSymbol(this.symbols[bookMark.geometry.type]);
        					}
        					this.userBookMarkNames.push(bookMark.attributes.BOOKMARK_NAME);
        					var objID = bookMark.attributes.OBJECTID
        					var bName = bookMark.attributes.BOOKMARK_NAME;
        					var bRemark = bookMark.attributes.REMARK;
        					this.addBookMark(bName,bRemark,false)
        				}));
 
        			}));

                },
                
                
                //新建/编辑书签窗口
                createOrEditBookMarkDiag:function(bID,bName,bRemark){
                	   if(Global.widgets.BookMarkEditDiag){
                		   Global.widgets.BookMarkEditDiag.destroy()
                	   }
                		require(["gistech/widgets/bookMark/BookMarkEdit",], lang.hitch(this,function (BookMarkEdit){
                     			this.BookMarkEditDialog=new BookMarkEdit({
                     				pos:{l:Math.ceil(document.body.clientWidth)/2-119,t:310} ,
                     				alignNode:dojo.byId("bookMarkEditDialog"), 
                                	close:true,
                                	hideWhenClickBody:true,
                                    map:Global.widgets.mapWidget.map,
                                    bID:bID,
                                    bName:bName,
                                    bRemark:bRemark
                                    } 
                                );
                     			 
                     			this.BookMarkEditDialog.startup();
                     			Global.widgets.BookMarkEditDiag=this.BookMarkEditDialog
                     		 
                     	}));
                },
 
                
                //保存
                _createOrEditBookMark:function(bID,name,remark){
//                	alert('bk-'+bID+name+remark)
                	if(bID){
                		//编辑
                		
//                    	var objDIV = dojo.create('div',{innerHTML:Global.widgets.BK.editTarget.parentElement.parentElement.innerHTML});
//                    	this.nowRowContainer = objDIV;
//                    	 
//                        var row = dojo.query(".row", this.nowRowContainer)[0];
//                        var rowInfo = dojo.query(".rowInfo", this.nowRowContainer)[0];
//                        var edit = dojo.query(".edit", this.nowRowContainer)[0];
//                        var remove = dojo.query(".remove", this.nowRowContainer)[0];
//                        var inputChangeName = dojo.query(".inputChangeName", this.nowRowContainer)[0];
//                        var inputID = dojo.query(".inputID", this.nowRowContainer)[0];
//                        var inputRemark = dojo.query(".inputRemark", this.nowRowContainer)[0];
//                        rowInfo.innerHTML = name;
//                        inputChangeName.value = name;
                        
                        Global.widgets.BK.editTarget.parentElement.parentElement.childNodes[2].value=name;
                        Global.widgets.BK.editTarget.parentElement.childNodes[0].nextElementSibling.innerHTML=name;
                        	
                        if(remark){
                        	Global.widgets.BK.editTarget.parentElement.parentElement.childNodes[6].value=remark;
                        }
                        
//                        dojo.style(inputChangeName, "display", "none");
//                        dojo.style(row, "display", "block");
                        
                		
                        this.updateBookMarkData(this.bookMarkPointLayerUrl,bID,name,remark);
                        this.updateBookMarkData(this.bookMarkLineLayerUrl,bID,name,remark);
                        this.updateBookMarkData(this.bookMarkPolygonLayerUrl,bID,name,remark);
                        
                	}else{
                		//新增
                		this.addBookMark(name,remark,true);
                	}
                	
             	   if(Global.widgets.BookMarkEditDiag){
            		   Global.widgets.BookMarkEditDiag.destroy()
            	   }
                	
                },
                //关闭事件
                onClose:function () {
                	topic.publish("BookMarkDestory","drowBar");
                    this.destroy();
                },
 
                initProjectData:function(x,y){
 
 
                	var url = "http://10.1.10.230:6080/arcgis/rest/services/SL/TG/FeatureServer/0";
        			var queryTask=new QueryTask(url); 
        			var query=new ArcQuery();
        			query.returnGeometry=true;
        			query.outFields=["*"];
        			for(var g=x;g<y;g++){ //5
            			query.where="OBJECTID>"+g*1000+" and OBJECTID<"+(g+1)*1000;
            			 
        				var projectUrl = "http://landa:6080/arcgis/rest/services/sddc/FeatureServer/2";
        				this.projectLayer = new FeatureLayer(projectUrl,{});
        				
            			queryTask.execute(query,lang.hitch(this,function(obj){
//            				debugger;
            				var arr = [];
            				array.forEach(obj.features,lang.hitch(this,function(res){
            					arr.push(res);
            				}));
            				console.log('add-->'+g);
            				this.projectLayer.applyEdits(arr,null,null,function(e){
            					console.log('ok'+g);
            					},function(e){
            						console.log('point-del-'+e);
            						console.log( e);
            					}
            				)
            				
            			}));
        			}

                },
                
            })
})